import { ref } from 'vue';
import { REQU, SignInInfoInvalidCondPair, getAssignedFileList, toFormData, useResp } from '@/net/requ.js';
import { fileContents, picState } from './use-task.js';
import { switchable } from './use-pic-switch.js';
import { Modal, message } from 'ant-design-vue';
import { initPicState } from '../index.js';
import { keydownCondPairs } from '../common.js';
import router from '@/router/index.js';

export const confirmModalProps = ref({ visible: false });
export const judgeModalProps = ref({ visible: false });

export function useJudgeModal(opts) {
  Object.assign(judgeModalProps.value, { visible: true, all: false }, opts);
}

export function judge(o) {
  return REQU('/api/task/assignedFileAudit', {
    method: 'POST',
    body: toFormData(Object.assign({}, o, {
      packageId: picState.value.curr.packageId,
      assignedFileId: picState.value.curr.id,
      note: picState.value.comments.length ? JSON.stringify(picState.value.comments) : '',
    }))
  })
  .then(useResp({
    succ: result => {
      if (Reflect.has(o, 'pass')) {
        picState.value.curr.auditStatus = o.pass ? 1 : 2;
        switchable.value.next ? ++picState.value.i : showConfirmNextPkg('已审核至最后一题');
      } else if (Reflect.has(o, 'wholePackagePass')) {
        picState.value.list.forEach(item => item.auditStatus = o.pass ? 1 : 2);
        showConfirmNextPkg('该包审核完毕');
      }
    },
    fail: R.cond([
      [result => -3 == result.code, R.compose(message.error, R.prop('message'))],
      SignInInfoInvalidCondPair(),
    ]),
  }));
}

export function comment(o) {
  picState.value.comments.push(o);
}

const PkgListOfUser = (pkgList, userId) => pkgList.filter(o => o.userId == userId);

export function showConfirmNextPkg(content) {
  const pkgInfo = JSON.parse(localStorage.getItem('pkgInfo'));
  const pkgList = JSON.parse(localStorage.getItem('pkgList'));
  const pkgListOfUser = PkgListOfUser(pkgList, pkgInfo.user);

  if (pkgListOfUser.findIndex(o => o.id == pkgInfo.pkg) == pkgListOfUser.length - 1) {
    confirmModalProps.value.visible = true;
    Modal.success({
      // here
      content: '最后一包审核完毕',
      okText: '返回任务列表',
      onOk: () => {
        confirmModalProps.value.visible = false;
        router.back();
      },
      onCancel: () => confirmModalProps.value.visible = false,
    });
    return;
  }

  confirmModalProps.value.visible = true;
  Modal.confirm({
    content,
    okText: '开始下一包',
    onOk: () => {
      confirmModalProps.value.visible = false;
      nextPkg();
    },
    cancelText: '返回任务列表',
    onCancel: () => {
      confirmModalProps.value.visible = false;
      router.back();
    },
  });
}

async function nextPkg() {
  const pkgInfo = JSON.parse(localStorage.getItem('pkgInfo'));
  const pkgList = JSON.parse(localStorage.getItem('pkgList'));
  const pkgListOfUser = PkgListOfUser(pkgList, pkgInfo.user);
  const nextPkg = pkgListOfUser[ pkgListOfUser.findIndex(o => o.id == pkgInfo.pkg) + 1 ];
  pkgInfo.pkg = nextPkg.id;
  localStorage.setItem('pkgInfo', JSON.stringify(pkgInfo));

  const fileList = await getAssignedFileList( pkgInfo.pkg ).then( R.prop('data') );
  const idValid = R.compose(R.lt(-1), R.findIndex(R.propEq('id', pkgInfo.file)));
  if ( R.compose(R.not, idValid)(fileList) ) {
    pkgInfo.file = fileList[0].id;
    localStorage.setItem('pkgInfo', JSON.stringify(pkgInfo));
  }
  fileContents.value = R.map( R.prop('fileContent'), fileList );

  document.querySelector('#label-area > p').innerHTML = trfNewline(fileContents.value[picState.value.i]);
  initPicState(fileList);
}

export function handleReject() {
  picState.value.comments.length ? judge({ pass: false }) : useJudgeModal({ action: '驳回' });
}

export default function useJudge() {
  keydownCondPairs.push(
    [event => 'g' == event.key && !event.ctrlKey && !event.shiftKey && !confirmModalProps.visible, () => judge({ pass: true })],
    [event => 'h' == event.key && !event.ctrlKey && !event.shiftKey && !confirmModalProps.visible, () => handleReject()],
  );
}
